package controllers

import (
	"ecomserver/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"strconv"
)

type GoodsController struct {
	beego.Controller
}
func GetCartCount(this *beego.Controller) int{
	name := this.GetSession("username")
	if name == nil{
		return 0
	}
	o := orm.NewOrm()
	var user models.User
	user.Name = name.(string)
	err := o.Read(&user, "Name")
	if err != nil{
		return 0
	}
	conn, err := redis.Dial(models.GetRedisAddr())
	if err != nil{
		return 0
	}
	defer conn.Close()
	rep,err := conn.Do("hlen", "cart_" + strconv.Itoa(user.Id))
	if err != nil{
		return 0
	}
	cartCount, _ := redis.Int(rep, err)

	return cartCount
}
func GetUser(c * beego.Controller) string {
	username := c.GetSession("username")
	if username == nil{
		c.Data["username"] = ""
	}else{
		c.Data["username"] = username.(string)
	}
	c.Data["nginx"] = "http://192.168.40.133:8888"
	return c.Data["username"].(string)
}
//展示首页
func (this *GoodsController) ShowIndex(){
	GetUser(&this.Controller)
	//获取类型数据
	o := orm.NewOrm()
	var goodsTypes [] models.GoodsType
	o.QueryTable("GoodsType").All(&goodsTypes)
	this.Data["goodsTypes"] = goodsTypes
	//获取轮播图
	var indexGoodsBanner [] models.IndexGoodsBanner
	o.QueryTable("IndexGoodsBanner").OrderBy("Index").All(&indexGoodsBanner)
	this.Data["indexGoodsBanner"] = indexGoodsBanner
	//获取促销商品数据
	var promotionGoods []models.IndexPromotionBanner
	o.QueryTable("IndexPromotionBanner").OrderBy("Index").All(&promotionGoods)
	this.Data["indexPromotionBanner"] = promotionGoods

	//首页展示商品数据
	goods := make([]map[string]interface{}, len(goodsTypes))
	for index, val := range goodsTypes{
		//获取对应类型的首页分类展示

		temp := make(map[string] interface{})
		temp["type"] = val
		goods[index] = temp
	}

	//var IndexTypeGoodsBanner [] models.IndexTypeGoodsBanner
	for _, val := range goods{
		var textGoods[]models.IndexTypeGoodsBanner
		var imgGoods []models.IndexTypeGoodsBanner
		//获取文字商品数据
		sel := o.QueryTable("IndexTypeGoodsBanner").RelatedSel("GoodsType","GoodsSKU").
			Filter("GoodsType", val["type"])

		sel.Filter("DisplayType", 0).OrderBy("Index").All(&textGoods)
		sel.Filter("DisplayType", 1).OrderBy("Index").All(&imgGoods)

		val["textGoods"] = textGoods
		val["imgGoods"] = imgGoods
	}
	this.Data["goods"] = goods
	this.Data["cartCount"] = GetCartCount(&this.Controller)
	this.TplName = "index.html"
}

func ShowLayout(c * beego.Controller) bool{
	GetUser(c)
	var goodsTypes []models.GoodsType
	o := orm.NewOrm()
	_, err := o.QueryTable("GoodsType").All(&goodsTypes)
	if err != nil{
		beego.Error("没有该商品类型", err)
		c.Redirect("/", 302)
		return false
	}
	c.Data["goodsTypes"] = goodsTypes
	c.Layout = "goods_layout.html"
	return true
}
//展示商品详情
func (this *GoodsController) ShowGoodsDetail(){

	goodsId, err := this.GetInt("id")
	if err != nil{
		beego.Error("浏览器请求错误")
		this.Redirect("/", 302)
		return
	}
	o := orm.NewOrm()
	var goodsSku models.GoodsSKU
	err = o.QueryTable("GoodsSKU").RelatedSel("Goods", "GoodsType").Filter("Id", goodsId).One(&goodsSku)

	if err != nil{
		beego.Error("没有该商品")
		this.Redirect("/", 302)
		return
	}
	var goodsNew []models.GoodsSKU

	_, err = o.QueryTable("GoodsSKU").RelatedSel("GoodsType").Filter("GoodsType", goodsSku.GoodsType).
		OrderBy("Time", "desc").Limit(2, 0).All(&goodsNew)
	ShowLayout(&this.Controller)
	this.Data["goodsNew"] = goodsNew
	this.Data["goodsku"] = goodsSku

	//保存用户浏览记录
	//判断用户是否登陆

	username := this.Data["username"]
	if username != ""{
		o := orm.NewOrm()
		var user models.User
		user.Name = username.(string)
		err := o.Read(&user, "Name")
		if err == nil{
			//用redis存储
			conn, err := redis.Dial(models.GetRedisAddr())
			if err != nil{
				beego.Info("redis连接错误", err)
			}else{
				conn.Send("lrem", "history_" + strconv.Itoa(user.Id), 0, goodsId)
				conn.Send("lpush", "history_" + strconv.Itoa(user.Id), goodsId)
				conn.Flush()//把缓冲区命令发到服务器
				conn.Close()
			}
		}
	}
	this.Data["cartCount"] = GetCartCount(&this.Controller)
	this.TplName = "detail.html"
}
func (this *GoodsController) splitGoodsPage(goods []models.GoodsSKU){
	//分页实现
	//假如每页两个，可以分成n/2页
	perPage := 3
	alllen := len(goods)
	allPage := 1
	if alllen < perPage{

	}else if alllen % perPage == 0{
		allPage = alllen / perPage
	}else{
		allPage = alllen / perPage + 1
	}
	pageList := make([]int, allPage)
	for i := 0; i < allPage; i++{
		pageList[i] = i + 1
	}

	//获取当前页码
	pageIndex, err := this.GetInt("page")
	if err != nil{
		pageIndex = 1
	}

	//检测
	if pageIndex < 1{
		pageIndex = 1
	}else if pageIndex > allPage{
		pageIndex = allPage
	}
	nextPage := pageIndex + 1

	this.Data["prePage"] = pageIndex - 1
	this.Data["nextPage"] = pageIndex + 1
	this.Data["activePage"] = pageIndex
	nextval := (nextPage - 1) * perPage
	if nextval > len(goods){
		nextval = len(goods)
	}
	this.Data["goods"] = goods[(pageIndex - 1) * perPage : nextval]
	this.Data["pages"] = pageList
}


//展示商品列表页
func (this *GoodsController) ShowList(){
	id, err := this.GetInt("typeId")
	if err != nil{
		beego.Info("请求路径错误", err)
		this.Redirect("/", 302)
		return
	}
	o := orm.NewOrm()

	//获取排序
	sortval, err := this.GetInt("sort")
	if err != nil{
		temp := this.GetSession("goodsSort")
		if temp == nil{
			sortval = 0
		}else {
			sortval = temp.(int)
		}
	}
	this.SetSession("goodsSort", sortval)


	ShowLayout(&this.Controller)

	var nowtype models.GoodsType
	nowtype.Id = id
	err = o.Read(&nowtype, "Id")
	if err != nil{
		beego.Info("错误", err)
		this.Redirect("/", 302)
		return
	}



	var goods []models.GoodsSKU
	sel :=  o.QueryTable("GoodsSKU").RelatedSel("GoodsType").Filter("GoodsType", nowtype)

	//获取商品
	switch sortval {
	case 0:
		_, err = sel.All(&goods)
		break
	case 1:
		_, err = sel.OrderBy("-Price").All(&goods)
		break
	case 2:
		_, err = sel.OrderBy("Sales").All(&goods)
		break
	default:
		_, err = sel.All(&goods)
		break
	}



	if err != nil{
		beego.Info("发生错误", err)
		this.Redirect("/", 302)
		return
	}

	//获取当前类型推荐数据
	var newGoods []models.GoodsSKU
	sel.OrderBy("-Time").Limit(2, 0).All(&newGoods)

	this.splitGoodsPage(goods)
	this.Data["sort"] = sortval
	this.Data["newGoods"] = newGoods
	this.Data["nowType"] = nowtype
	this.Layout = "goods_layout.html"
	this.TplName = "list.html"
}

func (this *GoodsController) HandleSearch(){
	goodsName := this.GetString("searchVal")
	o := orm.NewOrm()
	ShowLayout(&this.Controller)
	var goods []models.GoodsSKU
	if goodsName == ""{
		o.QueryTable("GoodsSKU").All(&goods)
		this.splitGoodsPage(goods)
		this.TplName = "search.html"
		return
	}
	//处理数据
	o.QueryTable("GoodsSKU").Filter("Name__icontains", goodsName).All(&goods)

	this.splitGoodsPage(goods)
	this.TplName = "search.html"
}